// Copyright DustedPixels.com 2008. All rights reserved.

package com.dustedpixels.jasmin.unit.memory;

import com.dustedpixels.jasmin.unit.Unit;

/**
 * @author micapolos@gmail.com (Michal Pociecha-Los)
 */
public final class RAM implements Unit {
  // (input) address bus
  public int ADDR = 0;
  
  // (input/output, tristate) data bus
  public int DATA;
  public int DATA_Z = 0;
  
  // (input, active high) write mode 
  public boolean WR = false;
  
  // (input, active high) request
  public boolean REQ = false;
  
  private final int addressMask;
  private final int[] memoryArray;
  
  /**
   * Creates memory of given address bus and data bus resolution.
   * 
   * @param addressPins address pins
   * @param dataPins data pins
   */
  public RAM(int addressPins, int[] dataArray) {
    this.addressMask = (1 << addressPins) - 1;
    this.memoryArray = dataArray;
  }
  
  public void updateEndPoints() {
    if (REQ) {
      if (WR) {
        DATA_Z = 0;
        memoryArray[ADDR & addressMask] = DATA;
      } else {
        DATA_Z = ~0;
        DATA = memoryArray[ADDR & addressMask];
      }
    } else {
      DATA_Z = 0;
    }
  }
}
